package com.sunther.document.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import com.sunther.document.Enum.CommonEnum;
import com.sunther.document.entity.User;
import com.sunther.document.service.RoleService;
import com.sunther.document.service.UserService;
import com.sunther.document.util.IpUtil;
import com.sunther.document.util.JwtUtils;
import com.sunther.document.util.RedisHelper;
import com.sunther.idb.common.util.WebResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author csb
 * @description: 登入相关
 * @date 2023/5/9 10:12
 */
@Api(value = "用户登录相关")
@RequestMapping("/login")
@RestController
public class LoginController {

    @Value("${token.key}")
    String key;

    @Resource
    private JwtUtils jwtUtils;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisHelper redisHelper;

    @PostMapping("login")
    @ApiOperation(value = "用户登录")
    public WebResult login(String name, String password, String capCode, HttpServletRequest request) {

        String ipAddr = IpUtil.getIpAddr(request);
        String code = ObjectUtil.toString(redisHelper.get(CommonEnum.IMG_CAP_CODE.getCode() + ipAddr));
        boolean verify = new MathGenerator().verify(code, capCode);
        if (!verify){
//            redisHelper.delete(CommonEnum.IMG_CAP_CODE.getCode() + ipAddr);
            return WebResult.failure("验证码错误");
        }

        // 1.根据用户名和密码查询用户信息
        User user = userService.getByName(name);
        String md5Password = SecureUtil.md5(password);
        Map<Integer, String> roleNameMap = roleService.getAllRoleNameMap();

        if (user == null) {
            return WebResult.failure("用户名或密码错误");
        } else if (!md5Password.equals(user.getPassword())) {
            return WebResult.failure("用户名或密码错误");
        } else {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("name", user.getName());
            map.put("nickName", user.getNickName());
            map.put("projectId", user.getProjectId());
            map.put("roleId", user.getRoleId());
            map.put("roleName", roleNameMap.get(user.getRoleId()));
            String token = jwtUtils.createJWT(user.getId(),user.getName(), user.getNickName(), user.getProjectId(), user.getRoleId(), roleNameMap.get(user.getRoleId()));

            return WebResult.success("登录成功",token);
        }
    }

    @GetMapping("getUserInfo")
    @ResponseBody
    public WebResult getUserInfo(HttpServletRequest request) {
        String token =  request.getHeader("Authorization");
        JWT jwt = JWT.of(token);
        return WebResult.success(jwt.getPayload());
    }


    @PostMapping("exit")
    @ApiOperation(value = "退出登录")
    public WebResult exit(HttpServletRequest request) {
        //清除session
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return WebResult.success("退出成功");
    }

    @GetMapping("/cap_code")
    @ApiOperation(value = "图形验证码")
    public void capCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置response响应
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(150, 40,4,0);
        // 自定义验证码内容为四则运算方式
        lineCaptcha.setGenerator(new MathGenerator(1));
        // 重新生成code
        lineCaptcha.createCode();

        //把图形验证码凭证放入cookie中
        Cookie cookie = new Cookie("login_cap_code",lineCaptcha.getCode());
        //cookie过期时间30分钟
        cookie.setMaxAge(3600);
        cookie.setPath("/");
        response.addCookie(cookie);

        //把凭证对应的验证码信息保存到reids（可从redis中获取）
        String ipAddr = IpUtil.getIpAddr(request);
        redisHelper.set(CommonEnum.IMG_CAP_CODE.getCode()+ipAddr,lineCaptcha.getCode(),60);

        //输出浏览器
        OutputStream out=response.getOutputStream();
        lineCaptcha.write(out);
        out.flush();
        out.close();
    }

    @PostMapping("/reg")
    @ApiOperation(value = "注册")
    public WebResult reg(@RequestBody User user,
                         @RequestParam String capCpde,
                         HttpServletRequest request) {
        return userService.reg(user,capCpde,request);
    }
}
